﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SimpleDbContextStorage.cs" company="">
//   
// </copyright>
// <summary>
//   The simple db context storage.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

#region

using System.Collections.Generic;
using System.Data.Entity;

#endregion

namespace Common.Data
{
    /// <summary>
    /// The simple db context storage.
    /// </summary>
    public class SimpleDbContextStorage : IDbContextStorage
    {
        /// <summary>
        /// The _storage.
        /// </summary>
        private readonly Dictionary<string, DbContext> _storage = new Dictionary<string, DbContext>();

        /// <summary>
        /// Returns the db context associated with the specified key or
        ///     null if the specified key is not found.
        /// </summary>
        /// <param name="key">
        /// The key.
        /// </param>
        /// <returns>
        /// The <see cref="DbContext"/>.
        /// </returns>
        public DbContext GetDbContextForKey(string key)
        {
            DbContext context;
            if (!_storage.TryGetValue(key, out context))
            {
                return null;
            }

            return context;
        }

        /// <summary>
        /// Stores the db context into a dictionary using the specified key.
        ///     If an object context already exists by the specified key,
        ///     it gets overwritten by the new object context passed in.
        /// </summary>
        /// <param name="key">
        /// The key.
        /// </param>
        /// <param name="context">
        /// The context.
        /// </param>
        public void SetDbContextForKey(string key, DbContext context)
        {
            _storage.Add(key, context);
        }

        /// <summary>
        /// Returns all the values of the internal dictionary of db contexts.
        /// </summary>
        /// <returns>
        /// The <see cref="IEnumerable"/>.
        /// </returns>
        public IEnumerable<DbContext> GetAllDbContexts()
        {
            return _storage.Values;
        }
    }
}